<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/freetrial'
import detailStore from '@/store/modules/cacheData'
import { GetAllData } from '@/api/modules/merchandiseControl'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  title: '',
  proImg: '',
  productId: 0,
  syProductId: 0,
  minVipLevel: 0,
  startTime: '',
  lotteryTime: '',
  qrcodeBgimg: '',
  shareTxt: '',
  shareImg: '',
  limitCon: 0,
  subscribeCon: 0,
  applyCon: 0,
  enable: true,
  sort: 0,
  buyUrl: '',
})

const OptionList = reactive({
  ProductOption: [],
  AllProductOption: [],
})

const rules = reactive({
  a: [
    { required: true, message: '请输入自定义排序', trigger: 'blur' },
  ],
})

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  if (url) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData() {
  const params = ruleForm.value
  // console.log(params)

  if (id) {
    // 编辑
    params.id = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'freetrialIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyFreetrial()
        router.push({ name: 'freetrialIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberFreetrial(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetFreetrial()
  }
  const productData: any = await GetAllData(qs.stringify({ ProductName: '', IsActive: true }))
  if (productData.succeeded) {
    OptionList.ProductOption = productData.data
    nextTick(() => {
      OptionList.ProductOption = productData.data
    })
  }
  const AllproductData: any = await GetAllData(qs.stringify({ ProductName: '' }))
  if (AllproductData.succeeded) {
    OptionList.AllProductOption = AllproductData.data
    nextTick(() => {
      OptionList.AllProductOption = AllproductData.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="标题">
              <el-input v-model="ruleForm.title" placeholder="请输入标题" />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="排序">
              <el-input v-model="ruleForm.sort" style="width: 300px;" placeholder="请输入排序" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="种草商品">
              <el-select v-model="ruleForm.productId" placeholder="请选择种草商品" filterable>
                <el-option
                  v-for="items in (OptionList.ProductOption as any)" :key="items.productId" :label="`${items.productId}-${items.productName}`" :value="items.productId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="试用商品">
              <el-select v-model="ruleForm.syProductId" placeholder="请选择试用商品" filterable>
                <el-option
                  v-for="items in (OptionList.AllProductOption as any)" :key="items.productId" :label="`${items.productId}-${items.productName}`" :value="items.productId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="申请人最低会员等级">
              <el-input v-model="ruleForm.minVipLevel" style="width: 300px;" placeholder="请输入申请人最低会员等级" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="上线时间" prop="openDate">
              <el-date-picker v-model="ruleForm.startTime" type="datetime" placeholder="请选择上线时间" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="开奖时间" prop="openDate">
              <el-date-picker v-model="ruleForm.lotteryTime" type="datetime" placeholder="请选择开奖时间" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareTxt" style="width: 300px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.shareImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareImg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="封面图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.proImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'proImg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="海报背景图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.qrcodeBgimg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'qrcodeBgimg')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
